package com.wclass.controller.app;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.wclass.common.DateUtil;
import com.wclass.common.ReturnObject;
import com.wclass.entity.*;
import com.wclass.interceptor.BaseContextHandler;
import com.wclass.model.CouresTaskInfoModel;
import com.wclass.model.UserMobile;
import com.wclass.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 课程作业 前端控制器
 * </p>
 *
 * @author 张浩高
 * @since 2018-12-20
 */
@Api(description = "课程作业管理")
@RestController
@RequestMapping("/couresTask")
public class CouresTaskController {
    @Autowired
    private ICouresTaskService iCouresTaskService;
    @Autowired
    private ICouresOrderService couresOrderService;
    @Autowired
    private ICouresTaskReplyService taskReplyService;
    @Autowired
    private ICouresTaskLikeService taskLikeService;
    @Autowired
    private IBaseAppUserService appUserService;
    @Autowired
    private IBaseFocusService iBaseFocusService;

    //************************************************************************************
    //*************************************学生端******************************************
    //************************************************************************************
    @ApiOperation("学生端-选择作业日期list")
    @RequestMapping(value = "/getTaskTimeList", method = RequestMethod.POST)
    public ReturnObject<Object> getTaskTimeList(@ApiParam("根据上课时间查询（yyyy-MM）") @RequestParam @DateTimeFormat(pattern = "yyyy-MM") Date date) {
        EntityWrapper<CouresTask> ew = new EntityWrapper<>();
        ew.eq("info.user_id", BaseContextHandler.getUserID());
        ew.between("info.crt_time", date, DateUtil.getMonthEndTime(new Date()));
        List<CouresTask> tasks = iCouresTaskService.selectList(ew);

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat df_value = new SimpleDateFormat("MM月dd日");

        List<Map<String, Object>> list = Lists.newArrayList();
        for (CouresTask info : tasks) {
            Map<String, Object> map = Maps.newHashMap();
            map.put(df.format(info.getCrtTime()), df_value.format(info.getCrtTime()) + "作业");
            list.add(map);
        }
        return new ReturnObject<>(0, "获取成功", list);
    }


    @ApiOperation("学生端-获取我的作业分页（我的课程）")
    @RequestMapping(value = "/getMyCouresTaskPage", method = RequestMethod.POST)
    public ReturnObject<Object> getMyCouresTaskPage(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                                    @ApiParam("页数") @RequestParam(defaultValue = "1") int offset) {
        EntityWrapper<CouresOrder> ew = new EntityWrapper();
        ew.eq("info.pay_person_id", BaseContextHandler.getUserID())
                .eq("info.pay_state", 1).groupBy("info.id");
        Page<CouresOrder> obj = couresOrderService.selectPage(new Page<>(offset, limit), ew);

        List<Map<String, Object>> list = Lists.newArrayList();
        for (CouresOrder order : obj.getRecords()) {
            Map<String, Object> map = iCouresTaskService.selectMapByCouresId(order.getCourseInfoId());
            list.add(map);
        }
        return new ReturnObject<>(0, "添加成功", obj.getTotal(), obj.getPages(), list);
    }


    @ApiOperation("学生端/老师端 - 课程下的作业完成情况")
    @RequestMapping(value = "/getPage", method = RequestMethod.POST)
    public ReturnObject<Object> getPage(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                        @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                        @ApiParam("课程id") @RequestParam Long courseInfoId,
                                        @ApiParam("类型，1：学生端，2：教师端") @RequestParam Integer type) {
        EntityWrapper<CouresTask> ew = new EntityWrapper<>();
        if (type == 1)
            ew.isNotNull("info.p_id");
        else
            ew.isNull("info.p_id");
        ew.eq("info.course_info_id", courseInfoId);
        ew.eq("info.user_id", BaseContextHandler.getUserID());
        ew.orderBy("info.crt_time", false);
        Page<CouresTask> obj = iCouresTaskService.selectPage(new Page<>(offset, limit), ew);

        for (CouresTask info : obj.getRecords()) {
            CouresTask stCouresTask = iCouresTaskService.selectById(info.getPId());
            if (stCouresTask != null) {
                info.setTitle(stCouresTask.getTitle());
                info.setRemarks(stCouresTask.getRemarks());
            }
            List<Integer> submitState = Lists.newArrayList();
            submitState.add(1);
            submitState.add(2);
            info.setFinished(iCouresTaskService.selectCount(new EntityWrapper<CouresTask>().in("submit_state", submitState).eq("course_info_id", courseInfoId)));
            info.setTotality(iCouresTaskService.selectCount(new EntityWrapper<CouresTask>().eq("course_info_id", courseInfoId).isNotNull("p_id")));
        }
        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getPages(), obj.getRecords());
    }

    @ApiOperation("学生端-获取课程下的作业(web端 我的作业-二级页面)")
    @RequestMapping(value = "/getPageForPC", method = RequestMethod.POST)
    public ReturnObject<Object> getPageForPC(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                             @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                             @ApiParam("课程id") @RequestParam Long courseInfoId,
                                             @ApiParam("（不传显示全部） 0：未提交，1：已提交，2：已打分，3：催交") Long state) {
        Map<String, Object> map = Maps.newHashMap();

        EntityWrapper<CouresTask> ew = new EntityWrapper<>();
        if (state != null) {
            ew.eq("stuTask.submit_state", state);
        }
        /*
         * 2018-03-19要求和手机端数据相同
         * ew.isNull("info.p_id");
         * ew.eq("stuTask.user_id", BaseContextHandler.getUserID());
         * ew.eq("info.course_info_id", courseInfoId);
         * ew.orderBy("info.crt_time", false);
         */
        ew.isNotNull("info.p_id");
        ew.eq("info.course_info_id", courseInfoId);
        ew.eq("info.user_id", BaseContextHandler.getUserID());
        ew.orderBy("info.crt_time", false);
        Page<CouresTask> obj = iCouresTaskService.selectPage(new Page<>(offset, limit), ew);

//        List<Map<String, Object>> list = Lists.newArrayList();

        for (CouresTask info : obj.getRecords()) {
            /*Map<String, Object> map_info = Maps.newHashMap();
            map_info.put("id", info.getId());
            map_info.put("crtTime", DateUtil.format(info.getCrtTime()));
            map_info.put("title", info.getTitle());
            map_info.put("remarks", info.getRemarks());
            map_info.put("week", DateUtil.getWeekOfDate(info.getCrtTime()));
            CouresTask stCouresTask = iCouresTaskService.selectOne(new EntityWrapper<CouresTask>().eq("user_id",
                    BaseContextHandler.getUserID()).eq("p_id", info.getId()));
            if (stCouresTask == null) {
                map_info.put("submitState", 0);
            } else {
                map_info.put("submitState", stCouresTask.getSubmitState());
                map_info.put("score", stCouresTask.getScore());
            }
            list.add(map_info);*/

            CouresTask stCouresTask = iCouresTaskService.selectById(info.getPId());
            if (stCouresTask != null) {
                info.setTitle(stCouresTask.getTitle());
                info.setRemarks(stCouresTask.getRemarks());
            }
            List<Integer> submitState = Lists.newArrayList();
            submitState.add(1);
            submitState.add(2);
            info.setFinished(iCouresTaskService.selectCount(new EntityWrapper<CouresTask>().in("submit_state", submitState).eq("course_info_id", courseInfoId)));
            info.setTotality(iCouresTaskService.selectCount(new EntityWrapper<CouresTask>().eq("course_info_id", courseInfoId).isNotNull("p_id")));
            info.setWeek(DateUtil.getWeekOfDate(info.getCrtTime()));
        }
        map.put("list", obj.getRecords());
        map.put("count", iCouresTaskService.getTaskCount(-1, BaseContextHandler.getUserID(), courseInfoId));
        map.put("finishCount", iCouresTaskService.getTaskCount(1, BaseContextHandler.getUserID(), courseInfoId));
        map.put("unfinishCount", iCouresTaskService.getTaskCount(0, BaseContextHandler.getUserID(), courseInfoId));
        map.put("correctCount", iCouresTaskService.getTaskCount(2, BaseContextHandler.getUserID(), courseInfoId));
        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getPages(), map);
    }

    @ApiOperation("学生端-提交作业")
    @RequestMapping(value = "/finishTask", method = RequestMethod.POST)
    public ReturnObject<CouresTask> finishTask(@ApiParam("作业id") @RequestParam Long id,
                                               @ApiParam("标题") String title,
                                               @ApiParam("封面图片") String cover,
                                               @ApiParam("备注") String remarks,
                                               @ApiParam("附件(json格式)") String attUrl) {
        CouresTask old = iCouresTaskService.selectById(id);
        old.setSubmitState(1);
        old.setTitle(title);
        old.setCover(cover);
        old.setRemarks(remarks);
        old.setAttUrl(attUrl);

        iCouresTaskService.updateById(old);
        return new ReturnObject<>(0, "提交成功", old);
    }

    @ApiOperation("学生端-获取作业详情")
    @RequestMapping(value = "/getinfo", method = RequestMethod.POST)
    public ReturnObject<CouresTaskInfoModel> getinfo(@ApiParam("学生作业id") @RequestParam Long id) {
        //我完成的作业内容
        CouresTask stCouresTask = iCouresTaskService.selectById(id);

        //老师布置的作内容
        CouresTask couresTask = iCouresTaskService.selectById(stCouresTask.getPId());
        couresTask.setIsLike(taskLikeService.selectCount(new EntityWrapper<CouresTaskLike>().eq("user_id", BaseContextHandler.getUserID()).eq("task_id", id)) > 0 ? 0 : 1);

        couresTask.setPostname(appUserService.selectOneById(couresTask.getUserId()).getPostname());
        int count = iBaseFocusService.selectCount(
                new EntityWrapper<BaseFocus>().eq("user_id", BaseContextHandler.getUserID()).eq("focus_user_id", couresTask.getUserId()).eq("state", 0));
        couresTask.setIsFocus(count);

        //同学完成的作业内容
        List<CouresTask> list = iCouresTaskService.selectList(new EntityWrapper<CouresTask>().eq("info.p_id", id).ne(
                "info.user_id", BaseContextHandler.getUserID()));
        return new ReturnObject<>(0, "获取成功", new CouresTaskInfoModel(couresTask, stCouresTask, list));
    }

    //************************************************************************************
    //*************************************老师端******************************************
    //************************************************************************************
    @ApiOperation("老师端-新增发布作业")
    @RequestMapping(value = "/addTask", method = RequestMethod.POST)
    public ReturnObject<CouresTask> addTask(@ApiParam("课程id") @RequestParam Long courseInfoId,
                                            @ApiParam("作业标题") @RequestParam String title,
                                            @ApiParam("备注") String remarks,
                                            @ApiParam("附件(json格式)") String attUrl) {
        CouresTask couresTask = new CouresTask(0, courseInfoId, BaseContextHandler.getUserID(), null
                , title, remarks, attUrl, null, null, 0, null, null, null, null, 0, 0, null, null, null, null, null);
        iCouresTaskService.insert(couresTask);
        //分发作业
        List<CouresOrder> list = couresOrderService.selectList(new EntityWrapper<CouresOrder>().eq("course_info_id", courseInfoId));
        for (CouresOrder info : list) {
            CouresTask stu_task = new CouresTask(0, courseInfoId,
                    info.getPayPersonId(), couresTask.getId(), null, null, null, null, null, 0, null, null, null, null, 0, 0, null, null, null, null, null);
            iCouresTaskService.insert(stu_task);
        }

        return new ReturnObject<>(0, "添加成功", couresTask);
    }

    @ApiOperation("老师端-删除发布作业")
    @RequestMapping(value = "/delTask", method = RequestMethod.POST)
    public ReturnObject delTask(@ApiParam("课程作业id") @RequestParam Long courseTaskId){
        iCouresTaskService.delete(new EntityWrapper<CouresTask>().eq("p_id", courseTaskId));
        iCouresTaskService.deleteById(courseTaskId);
        return new ReturnObject(0, "删除成功");
    }

    @ApiOperation("老师端-提交作业批改情况")
    @RequestMapping(value = "/correctTask", method = RequestMethod.POST)
    public ReturnObject<CouresTask> correctTask(@ApiParam("作业id") @RequestParam Long id,
                                                @ApiParam("评价") String evaluate,
                                                @ApiParam("评分（0:A,1:B,2:C,3:D）") Integer score) {
        CouresTask old = iCouresTaskService.selectById(id);
        old.setEvaluate(evaluate);
        old.setScore(score);
        old.setSubmitState(2);
        iCouresTaskService.updateById(old);
        return new ReturnObject<>(0, "提交成功", old);
    }

    @ApiOperation("老师端-获取学生作业详情")
    @RequestMapping(value = "/getstudentInfo", method = RequestMethod.POST)
    public ReturnObject<CouresTask> getstudentInfo(@ApiParam("作业id") @RequestParam Long id) {
        CouresTask info = iCouresTaskService.selectById(id);
        info.setIsLike(taskLikeService.selectCount(new EntityWrapper<CouresTaskLike>().eq("user_id", BaseContextHandler.getUserID()).eq("task_id", id)) > 0 ? 0 : 1);
        return new ReturnObject<>(0, "获取成功", info);
    }

    @ApiOperation("老师端-获取学生作业列表")
    @RequestMapping(value = "/teacherGetPage", method = RequestMethod.POST)
    public ReturnObject<List<CouresTask>> teacherGetPage(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                                         @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                                         @ApiParam("作业id") @RequestParam Long id,
                                                         @ApiParam("提交状态（0：未提交，1：已提交，2：已打分，3：已催交）") @RequestParam Integer submitState) {

        CouresTask couresTask = iCouresTaskService.selectById(id);

        EntityWrapper<CouresTask> ew = new EntityWrapper<>();
        ew.eq("info.p_id", couresTask.getPId()).eq("info.submit_state", submitState).orderBy("info.crt_time", false);
        Page<CouresTask> obj = iCouresTaskService.selectPage(new Page<>(offset, limit), ew);
        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getPages(), obj.getRecords());
    }

    @ApiOperation("老师端-单个学生催交")
    @RequestMapping(value = "/callStudentTask", method = RequestMethod.POST)
    public ReturnObject<Object> callStudentTask(@ApiParam("作业id") @RequestParam Long id,
                                                @ApiParam("学生id") @RequestParam Long userId) {
        EntityWrapper<CouresTask> ew = new EntityWrapper<>();
        ew.eq("user_id", userId).eq("p_id", id).eq("submit_state", 0);
        List<CouresTask> list = iCouresTaskService.selectList(ew);

        CouresTask info = list.size() > 0 ? list.get(0) : null;
        if (info != null) {
            info.setSubmitState(3);
            iCouresTaskService.updateById(info);
        }
        return new ReturnObject<>(0, "催交成功");
    }

    @ApiOperation("老师端-一键指定作业催交")
    @RequestMapping(value = "/callTasks", method = RequestMethod.POST)
    public ReturnObject<Object> callTasks(@ApiParam("作业id") @RequestParam Long id) {
        EntityWrapper<CouresTask> ew = new EntityWrapper<>();
        ew.eq("submit_state", 0).eq("p_id", id);
        List<CouresTask> list = iCouresTaskService.selectList(ew);

        for (CouresTask info : list) {
            info.setSubmitState(3);
            iCouresTaskService.updateById(info);
        }
        return new ReturnObject<>(0, "催交成功");
    }

    //************************************************************************************
    //*************************************通用类******************************************
    //************************************************************************************

    @ApiOperation("获取指定学生的作业(发布)分页")
    @RequestMapping(value = "/getCouresTaskPageByUserId", method = RequestMethod.POST)
    public ReturnObject<Object> getCouresTaskPageByUserId(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                                          @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                                          @ApiParam("学生id") @RequestParam Long userId) {
        EntityWrapper<CouresTask> ew = new EntityWrapper();
        ew.eq("info.user_id", userId);
        ew.eq("info.submit_state", 2);
        Page<CouresTask> obj = iCouresTaskService.selectPage(new Page<>(offset, limit), ew);


        return new ReturnObject<>(0, "添加成功", obj.getTotal(), obj.getPages(), obj.getRecords());
    }


    @ApiOperation("指定用户作业详情")
    @RequestMapping(value = "/getTaskInfoById", method = RequestMethod.POST)
    public ReturnObject<CouresTask> getTaskInfoById(@ApiParam("作业id") @RequestParam Long id) {
        CouresTask couresTask = iCouresTaskService.selectById(id);
        couresTask.setIsLike(taskLikeService.selectCount(new EntityWrapper<CouresTaskLike>().eq("user_id", BaseContextHandler.getUserID()).eq("task_id", id)) > 0 ? 0 : 1);
        return new ReturnObject<>(0, "获取成功", couresTask);
    }

    @ApiOperation("作业新增评论")
    @RequestMapping(value = "/addTaskReply", method = RequestMethod.POST)
    public ReturnObject<CouresTask> addTaskReply(@ApiParam("作业id") @RequestParam Long taskId,
                                                 @ApiParam("评论内容") @RequestParam String content) {
        //进行编码
        content = new String(Base64.getEncoder().encode(content.getBytes()));

        CouresTaskReply reply = new CouresTaskReply();
        reply.setUserId(BaseContextHandler.getUserID());
        reply.setContent(content);
        reply.setTaskId(taskId);
        reply.setCrtTime(new Date());
        taskReplyService.insert(reply);

        CouresTask couresTask = iCouresTaskService.selectById(taskId);
        couresTask.setCommentNum(taskReplyService.selectCount(new EntityWrapper<CouresTaskReply>().eq("task_id", taskId)));
        iCouresTaskService.updateById(couresTask);

        return new ReturnObject<>(0, "点评成功");
    }

    @ApiOperation("新增作业评论的评论")
    @RequestMapping(value = "/addTaskReplyReply", method = RequestMethod.POST)
    public ReturnObject<CouresTask> addTaskReplyReply(@ApiParam("作业评论id") @RequestParam Long replyId,
                                                      @ApiParam("评论内容") @RequestParam String content) {
        //进行编码
        content = new String(Base64.getEncoder().encode(content.getBytes()));

        CouresTaskReply couresTaskReply = taskReplyService.selectById(replyId);

        CouresTaskReply reply = new CouresTaskReply();
        reply.setUserId(BaseContextHandler.getUserID());
        reply.setContent(content);
        reply.setTaskId(couresTaskReply.getTaskId());
        reply.setPId(replyId);
        reply.setCrtTime(new Date());
        taskReplyService.insert(reply);

        CouresTask couresTask = iCouresTaskService.selectById(couresTaskReply.getTaskId());
        couresTask.setCommentNum(taskReplyService.selectCount(new EntityWrapper<CouresTaskReply>().eq("task_id", couresTaskReply.getTaskId())));
        iCouresTaskService.updateById(couresTask);

        return new ReturnObject<>(0, "点评成功");
    }

    @ApiOperation("作业删除评论")
    @RequestMapping(value = "/delTaskReply", method = RequestMethod.POST)
    public ReturnObject<CouresTask> delTaskReply(@ApiParam("作业id") @RequestParam Long replyId) {
        taskReplyService.deleteById(replyId);
        return new ReturnObject<>(0, "删除成功");
    }

    @ApiOperation("作业点赞/取消点赞")
    @RequestMapping(value = "/taskInfoLike", method = RequestMethod.POST)
    public ReturnObject<CouresTask> taskInfoLike(@ApiParam("作业id") @RequestParam Long taskId,
                                                 @ApiParam("点赞状态 0 点赞 1 取消点赞") @RequestParam Integer state) {
        CouresTask couresTask = iCouresTaskService.selectById(taskId);
        if (state == 0) {
            List<CouresTaskLike> likes = taskLikeService.selectList(new EntityWrapper<CouresTaskLike>().eq("task_id", taskId));
            if (likes.size() == 0) {
                CouresTaskLike like = new CouresTaskLike();
                like.setCrtTime(new Date());
                like.setTaskId(taskId);
                like.setUserId(BaseContextHandler.getUserID());
                taskLikeService.insert(like);
            }
        }
        if (state == 1) {
            List<CouresTaskLike> likes = taskLikeService.selectList(new EntityWrapper<CouresTaskLike>().eq("task_id", taskId));
            if (likes.size() > 0) {
                CouresTaskLike info = likes.get(0);
                taskLikeService.deleteById(info.getId());
            }
        }
        couresTask.setLikeNum(taskLikeService.selectCount(new EntityWrapper<CouresTaskLike>().eq("task_id", taskId)));
        iCouresTaskService.updateById(couresTask);

        return new ReturnObject<>(0, "操作成功", couresTask);
    }

    @ApiOperation("获取作业点赞人员分页")
    @RequestMapping(value = "/getTaskLikeUserPage", method = RequestMethod.POST)
    public ReturnObject<List<UserMobile>> getTaskLikeUserPage(@ApiParam("作业id") @RequestParam Long taskId,
                                                              @ApiParam("点赞状态 0 点赞 1 取消点赞") @RequestParam Integer state) {
        List<CouresTaskLike> likes = taskLikeService.selectList(new EntityWrapper<CouresTaskLike>().eq("task_id", taskId));
        List<UserMobile> list = Lists.newArrayList();
        for (CouresTaskLike info : likes) {
            BaseAppUser appUser = appUserService.selectById(info.getUserId());
            UserMobile userMobile = new UserMobile();
            appUser.setPassword(null);
            BeanUtils.copyProperties(appUser, userMobile);
            list.add(userMobile);
        }
        return new ReturnObject<>(0, "操作成功", list);
    }

    @ApiOperation("获取作业评论分页")
    @RequestMapping(value = "/getTaskReplyPage", method = RequestMethod.POST)
    public ReturnObject<List<CouresTaskReply>> getTaskReplyPage(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                                                @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                                                @ApiParam("作业id") @RequestParam Long taskId) throws Exception {
        EntityWrapper<CouresTaskReply> ew = new EntityWrapper<>();
        ew.eq("task_id", taskId);
        Page<CouresTaskReply> obj = taskReplyService.selectPage(new Page<>(offset, limit), ew);

        for (CouresTaskReply info : obj.getRecords()) {
            //进行解码
            info.setContent(new String(Base64.getDecoder().decode(info.getContent().getBytes()),"utf-8"));

            if (info.getPId() != null){
                List<CouresTaskReply> list = Lists.newArrayList();
                CouresTaskReply reply = taskReplyService.selectById(info.getPId());
                //进行解码
                reply.setContent(new String(Base64.getDecoder().decode(reply.getContent().getBytes()),"utf-8"));

                UserMobile childUser = new UserMobile();
                BaseAppUser user = appUserService.selectById(reply.getUserId());
                user.setPassword(null);
                BeanUtils.copyProperties(user, childUser);
                reply.setUserInfo(childUser);

                list.add(reply);
                info.setChildReplyList(list);
            }

            UserMobile userMobile = new UserMobile();
            BaseAppUser appUser = appUserService.selectById(info.getUserId());
            appUser.setPassword(null);
            BeanUtils.copyProperties(appUser, userMobile);
            info.setUserInfo(userMobile);
        }

        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getPages(), obj.getRecords());
    }

    @ApiOperation("web——获取作业评论分页")
    @RequestMapping(value = "/getWebTaskReplyPage", method = RequestMethod.POST)
    public ReturnObject<List<CouresTaskReply>> getWebTaskReplyPage(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                                                   @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                                                   @ApiParam("作业id") @RequestParam Long taskId) throws Exception {
        EntityWrapper<CouresTaskReply> ew = new EntityWrapper<>();
        ew.eq("task_id", taskId).orderBy("crt_time", false).isNull("p_id");
        Page<CouresTaskReply> obj = taskReplyService.selectPage(new Page<>(offset, limit), ew);

        //获取帖子评论的子评论列表
        for (CouresTaskReply taskReply : obj.getRecords()) {
            //进行解码
            taskReply.setContent(new String(Base64.getDecoder().decode(taskReply.getContent().getBytes()),"utf-8"));

            List<CouresTaskReply> childList = Lists.newArrayList();
            foreachGetChildReply(childList, taskReply, taskId, 1, 5);
            //对子评论按时间进行倒序排序
            Collections.sort(childList, new SortByCrtTime());
            taskReply.setChildReplyList(childList);

            UserMobile userMobile = new UserMobile();
            BaseAppUser appUser = appUserService.selectById(taskReply.getUserId());
            appUser.setPassword(null);
            BeanUtils.copyProperties(appUser, userMobile);
            taskReply.setUserInfo(userMobile);
        }

        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getPages(), obj.getRecords());
    }

    class SortByCrtTime implements Comparator {
        public int compare(Object obj1, Object obj2) {
            CouresTaskReply reply_1 = (CouresTaskReply) obj1;
            CouresTaskReply reply_2 = (CouresTaskReply) obj2;
            if (reply_1.getCrtTime().getTime() > reply_2.getCrtTime().getTime())
                return -1;
            return 1;
        }
    }

    /**
     * 获取帖子评论的子评论列表
     */
    public void foreachGetChildReply(List<CouresTaskReply> childList, CouresTaskReply taskReply, Long taskId, Integer page, Integer limit) throws Exception {
        EntityWrapper<CouresTaskReply> ew = new EntityWrapper<>();
        ew.orderBy("crt_time", false).eq("task_id", taskId).eq("p_id", taskReply.getId());
        List<CouresTaskReply> list;
        if (page != null && limit != null) {
            Page<CouresTaskReply> obj = taskReplyService.selectPage(new Page<>(page, limit), ew);
            list = obj.getRecords();
        } else {
            list = taskReplyService.selectList(ew);
        }
        for (CouresTaskReply childReply : list) {
            //进行解码
            childReply.setContent(new String(Base64.getDecoder().decode(childReply.getContent().getBytes()),"utf-8"));

            UserMobile userMobile = new UserMobile();
            BaseAppUser appUser = appUserService.selectById(childReply.getUserId());
            appUser.setPassword(null);
            BeanUtils.copyProperties(appUser, userMobile);
            childReply.setUserInfo(userMobile);

            childList.add(childReply);
            foreachGetChildReply(childList, childReply, taskId, page, limit);
        }
    }
}

